package com.lsq.controller;

import com.alibaba.fastjson.JSON;
import com.lsq.common.AjaxResult;
import com.lsq.common.RequestMappingAnalysis;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @version 1.0
 * @author:罗苏琴
 * @Date 2024/12/13 下午5:09
 */
@WebServlet(name="DispatcherServlet",urlPatterns = "/")
public class DispatcherServlet extends HttpServlet {
    Map<String,String> urlMapping = new HashMap<String,String>();

    @Override
    public void init() throws ServletException {
        super.init();


        try {
            urlMapping.putAll(RequestMappingAnalysis.getRequestMapping("com.lsq.controller"));
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (resp.getContentType() == null) {
            resp.setContentType("application/json;charset=UTF-8");
        }

        System.out.println("进入DispatcherServlet");
        String urlStr = req.getRequestURI();

        //通过反射获取到class实例
        String urlValue = urlMapping.get(urlStr);

        PrintWriter out = resp.getWriter();
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setCode(500);

        if (urlValue == null) {
            ajaxResult.setCode(404);
            ajaxResult.setMsg("你访问的路径不存在");
            out.print(JSON.toJSONString(ajaxResult));
        }

        String className = urlValue.substring(0,urlValue.lastIndexOf("."));
        String methodName = urlValue.substring(urlValue.lastIndexOf(".") + 1);


        try {
            Class clzz = Class.forName(className);

            Object o = clzz.getConstructor().newInstance();

            Method method = clzz.getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);

            ajaxResult  = (AjaxResult) method.invoke(o,req,resp);
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException(ex);
        } catch (NoSuchMethodException ex) {
            throw new RuntimeException(ex);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        out.print(JSON.toJSONString(ajaxResult));
    }

}
